package day14;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class Server2 {
    //保存进入了聊天室的客户端对象
    static List<Socket> list = new ArrayList<>();

    public static void main(String[] args) throws IOException {
        ServerSocket server = new ServerSocket(9999);
        while (true) {
            Socket client = server.accept();
            list.add(client);   //类似于加群
            System.out.println("聊天群一共有: " + list.size() + "人");
            //创建线程：负责多次客户端读取，负责给其他所有客户端在写入
            new ServerThread2(client).start();
        }
    }
}

class ServerThread2 extends Thread {
    Socket client;

    public ServerThread2(Socket client) {
        this.client = client;
    }

    @Override
    public void run() {
        try {
            BufferedReader br = new BufferedReader(
                    new InputStreamReader(client.getInputStream()));
            while (true) {
                //读取当前客户端数据
                String msg = br.readLine();
                if (msg != null) {
                    System.out.println(msg);
                    //如果客户端写入的数据  包含了esc就表示退出聊天室
                    if (msg.contains("esc")) {
                        Server2.list.remove(client);
                        int i = msg.indexOf("说");
                        String name = msg.substring(0, i);
                        System.out.println(name + "已退出, 聊天室的人数:" + Server2.list.size());
                        break;  //return也可以
                    }

                    //向其他客户端写入
                    for (Socket s : Server2.list) {
                        if (s != client) {
                            //如果有的客户端没有正常关闭，如果在写入数据就会出现异常
                            //就会导致后续的循环不会执行 所以这里要做try/catch
                            try {
                                s.getOutputStream().write((msg + "\n").getBytes());
                            } catch (IOException e) {
                            }
                        }
                    }

                }
            }

        } catch (Exception e) {

        }
    }
}